#include "DatabaseManager.h"
#include "mysql_connection_pool.h"
#include <iostream>
#include <thread>
#include <vector>

void initDatabase() {
    DatabaseInfo dbInfo;
    dbInfo.host = "localhost";
    dbInfo.port = 3306;
    dbInfo.user = "root";
    dbInfo.password = "950330g.G";
    dbInfo.database = "testdb";
    dbInfo.maxConnections = 10;
    
    MySQLConnectionPool::getInstance()->initPool(dbInfo, 5);
}

void testDatabaseOperations(int threadId) {
    for (int i = 0; i < 3; i++) {
        DatabaseManager dbMgr;
        
        // Example: Create table
        std::string createTableSQL = "CREATE TABLE IF NOT EXISTS test_table (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))";
        if (dbMgr.execute(createTableSQL)) {
            std::cout << "Thread " << threadId << ": Table created successfully" << std::endl;
        } else {
            std::cout << "Thread " << threadId << ": Failed to create table" << std::endl;
        }
        
        // Example: Insert data
        std::string insertSQL = "INSERT INTO test_table (name) VALUES ('Test" + std::to_string(threadId) + "_" + std::to_string(i) + "')";
        if (dbMgr.execute(insertSQL)) {
            std::cout << "Thread " << threadId << ": Data inserted successfully" << std::endl;
        } else {
            std::cout << "Thread " << threadId << ": Failed to insert data" << std::endl;
        }
        
        // Example: Query data
        std::string selectSQL = "SELECT id, name FROM test_table ORDER BY id DESC LIMIT 1";
        if (dbMgr.executeQuery(selectSQL)) {
            char* id = dbMgr.getField("id");
            char* name = dbMgr.getField("name");
            if (id && name) {
                std::cout << "Thread " << threadId << ": Retrieved - ID: " << id << ", Name: " << name << std::endl;
            }
        } else {
            std::cout << "Thread " << threadId << ": Failed to query data" << std::endl;
        }
        
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

int main() {
    try {
        // Initialize database connection pool
        initDatabase();
        
        // Create multiple threads to test connection pool
        std::vector<std::thread> threads;
        for (int i = 0; i < 5; i++) {
            threads.emplace_back(testDatabaseOperations, i);
        }
        
        // Wait for all threads to complete
        for (auto& t : threads) {
            t.join();
        }
        
        std::cout << "All database operations completed successfully!" << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
}